/*
 *
 *  * Copyright (c) 2015. For Intelligent Group.
 *
 */

package com.intelligent.ispc.export.yield;

import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.foundation.poi.ExCell;
import com.intelligent.ispc.foundation.poi.ExSheet;
import com.intelligent.ispc.foundation.poi.SampleExcelBuilder;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.*;
import java.util.List;


/**
 * draw Yield excel
 *
 * Created by Alice on 2016/9/26.
 */
public class YieldExcelBuilder extends SampleExcelBuilder {
    private static Logger logger = LoggerFactory.getLogger(YieldExcelBuilder.class);
    private Integer operator;
    private Integer trial;

    /**
     * Constructor
     *
     * @param operator operator
     * @param trial    trail
     */
    public YieldExcelBuilder(Integer operator, Integer trial) {
        this.operator = operator;
        this.trial = trial;
    }

    /**
     * draw excel of Yield
     *
     * @param path    file path of exporting
     * @param factory class of filling data to cell
     */
    public void drawExcel(String path, YieldExportWorker factory) {
        List<ExSheet> sheet = factory.getSheets();
        SXSSFWorkbook currentWb = factory.getCurrentWorkbook();
        OutputStream out = null;
        try {
            out = new FileOutputStream(path);
            for (int i = 0; i < sheet.size(); i++) {
                drawYieldSheet(currentWb, sheet.get(i), i);
            }
            currentWb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("can not find directory:" + e);
            throw new ApplicationException(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * draw excel and set Column Width  of Yield
     * @param workbook
     * @param exSheet
     * @param i    index that means which sheet
     */
    private void drawYieldSheet(SXSSFWorkbook workbook, ExSheet exSheet, int i) {
        String name = exSheet.getName();
        logger.debug("sheet name:{}", name);
        List<ExCell> exCells = exSheet.getExCells();
        SXSSFSheet sheet = workbook.createSheet(name);
        int column = 0;
        final int firstColumnWidth = 25;
        final int otherColumnWidth = 15;

        if (i == 0) {
            sheet.setColumnWidth(column, firstColumnWidth * 256);
        }
        sheet.setDefaultColumnWidth(otherColumnWidth);

        drawSheet(exCells, sheet, workbook);
        try {
            sheet.flushRows();
        } catch (IOException e) {
            e.printStackTrace();
        }
        sheet = null;
    }
}
